<script setup lang="ts">
defineOptions({
  name: 'CommentSection',
})

import { onMounted, watch } from 'vue'
import { useCommentStore } from '@/stores/useCommentStore'
import { CommentSystem } from '@/components/common/comment'

interface Props {
  articleId: string
}

const props = defineProps<Props>()

const commentStore = useCommentStore()

// 监听 articleId 变化，重新加载评论
watch(
  () => props.articleId,
  (newArticleId) => {
    if (newArticleId) {
      commentStore.resetState()
      commentStore.fetchComments({
        articleId: newArticleId,
        page: 1,
        limit: 20,
        parentId: null,
      })
    }
  },
  { immediate: true },
)

onMounted(() => {
  if (props.articleId) {
    commentStore.fetchComments({
      articleId: props.articleId,
      page: 1,
      limit: 20,
      parentId: null,
    })
  }
})
</script>

<template>
  <div class="comment-section">
    <CommentSystem
      :comments="commentStore.topLevelComments"
      :loading="commentStore.loading"
      :loading-more="commentStore.loadingMore"
      :has-more="commentStore.hasMore"
      :replies-data="commentStore.repliesData"
      :show-replies="commentStore.showReplies"
      :has-more-replies="commentStore.hasMoreReplies"
      :submitting="commentStore.submitting"
      :total-comments="commentStore.totalComments"
      @load-more="commentStore.loadMoreComments(props.articleId)"
      @toggle-replies="commentStore.toggleRepliesDisplay"
      @load-more-replies="commentStore.loadMoreReplies"
      @toggle-like="(commentId) => commentStore.toggleLike(commentId, '1')"
      @create-comment="
        (content, mentionedUsers) =>
          commentStore.createComment({
            articleId: props.articleId,
            content,
            authorId: '1',
            mentionedUsers,
          })
      "
      @create-reply="
        (parentId, content, mentionedUsers) =>
          commentStore.createReply(parentId, {
            articleId: props.articleId,
            content,
            authorId: '1',
            mentionedUsers,
          })
      "
    />
  </div>
</template>

<style scoped>
.comment-section {
  background-color: hsl(var(--b1));
  border-radius: 1rem;
  padding: 2rem;
  margin-top: 2rem;
}
</style>
